package com.simplefun;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class SimplefunServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");

		storeContact(createContact());
		storeContact(createContact());

		resp.getWriter().println("Hello, there world and " + getAllContactNames());		

	}
	
	




	private Contact createContact() {
		String name = "ok" + createTwoRandomDigits();
		System.out.println("name");
		int closeness = 3;
		Contact contact = new Contact(name, closeness, false);
		return contact;
	}

	private static String getAllContactNames() {
		String names = "";
		
		List<Contact> allContacts = getAllContacts();
		for (Contact contact : allContacts) {
			names += contact.getName() + " ";
		}
		
		return names;
	}

	@SuppressWarnings("unchecked")
	private static List<Contact> getAllContacts() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + Contact.class.getName();
		List<Contact> contacts = (List<Contact>) pm.newQuery(query).execute();
		return contacts;
	}

	private void storeContact(Contact contact) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(contact);
		} finally {
			pm.close();
		}
	}

	private static int createTwoRandomDigits() {
		return (int)(Math.random() * 100);
	}
}
